package com.cml.batisext.core.repository.mybatis.base.sqlprovider;

import java.lang.reflect.Field;
import java.util.List;

import com.cml.batisext.core.repository.mybatis.annotations.DbField;
import com.cml.batisext.core.repository.mybatis.annotations.DbTable;
import com.cml.batisext.core.repository.mybatis.base.BaseDaoSqlProvider;

/**
 * 通用接口的delete方法的sql生成器,目前仅适用于mysql
 * @author lwh
 *
 */
public class BaseDaoDeleteSqlProvider extends BaseDaoSqlProvider{

	public String doBuildSql(Object param ,Class<?> beanType) throws Exception {
		
		String tableName = beanType.getAnnotation(DbTable.class).table();
		
		if(param instanceof Long){
			return "delete from " + tableName + " where id = " + param;
		}else{
			String sql = "delete from " + tableName;
			
			List<Field> fields = getAllDbField(beanType);
			
			String tmpColumnName = null;
			Class<?> tmpColumnType = null;
			String sqlWhere = "    ";
			boolean hasWhere = false;
			Object fieldValue = null;
			
			for(Field f : fields){
				
				DbField field = f.getAnnotation(DbField.class);
				// 只对标注了为数据库字段的属性进行处理
				if (field == null) {
					continue;
				}

				tmpColumnName = getColumnName(f, field);
				tmpColumnType = getColumnType(f, field);
				fieldValue = getColumnValue(param, f, beanType);

				if (fieldValue != null) {
					hasWhere = true;
					sqlWhere += tmpColumnName + " = "
							+ setupFieldValue(tmpColumnType, fieldValue)
							+ " and ";
				}
			}
			
			if(hasWhere){
				sql += " where " + sqlWhere.substring(0,sqlWhere.length() - 4);
			}
			return sql;
		}
	}
	
}
